package promote.brozen.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.ByteBuffer;

/**
 * @author Brozen
 * @date 2020/9/30 3:21 PM
 * @email brozen@qq.com
 */
public class ToNIOBuffer {


    public static void main(String[] args) {
//        nioBuffer();
        nioBufferCount();
    }

    private static void nioBufferCount() {
        ByteBuf buf = Unpooled.directBuffer();
        buf.writeBytes(new byte[]{1, 2, 3, 4, 5});
        System.out.println("nioBufferCount :" + buf.nioBufferCount());

        ByteBuffer buffer0 = buf.nioBuffer();
        System.out.println("nioBufferCount :" + buf.nioBufferCount());

        buf.writeBytes(new byte[]{6, 7, 8, 9, 0});
        ByteBuffer buffer1 = buf.nioBuffer();
        System.out.println("nioBufferCount :" + buf.nioBufferCount());

        System.out.println("buffer0 == buffer1 :" + (buffer0 == buffer1));
        System.out.println("nioBuffers.length = " + buf.nioBuffers().length);


    }

    private static void nioBuffer() {
        ByteBuf buf = Unpooled.wrappedBuffer(new byte[]{1, 3, 5, 7, 9, 10});
        ByteBuffer buffer = buf.nioBuffer();

        // buffer随机读
        System.out.println(buffer.get(1));

        // buf随机写
        buf.setByte(1, 99);

        // 再读，值相同，共享底层数组
        System.out.println(buffer.get(1));

        // buffer随机写，也影响到buf
        buffer.put(1, (byte) 98);
        System.out.println(buf.getByte(1));
    }


}
